package edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.component.SoilComponent;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.entity.DeviceMonitorRecordEntity;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.entity.DeviceSoilRecordEntity;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.entity.GreenhouseEntity;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.service.DeviceMonitorRecordService;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.service.DeviceSoilRecordService;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.service.GreenhouseService;
import edu.ynu.se.xiecheng.achitectureclass.digitalagriculture.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 温室控制器
 * 设计原则体现：
 * 1. MVC架构模式 - 作为Controller层处理温室相关的请求和响应
 * 2. 依赖注入(DI)原则 - 通过@Autowired注入所需服务
 */
@RequestMapping("/greenhouse")
@RestController
public class GreenhouseController {

    // 依赖注入原则 - 使用接口而非具体实现，降低耦合度
    @Autowired
    private GreenhouseService greenhouseService;
    @Autowired
    private DeviceSoilRecordService deviceSoilRecordService;
    @Autowired
    private DeviceMonitorRecordService deviceMonitorRecordService;

    @RequestMapping("/getTrData")
    public String getTrData() {
        String data = deviceSoilRecordService.getTrDat("2025-1-3", "");
        System.out.println(data);
        return "success";
    }

    /**
     * 获取首页数据
     * 设计原则体现：
     * 1. 单一职责原则 - 方法负责整合首页所需的所有数据
     * 2. 分层架构 - Controller调用多个Service处理业务逻辑
     * 3. 数据封装 - 使用JSONObject封装返回数据
     */
    @RequestMapping("/getHomeData")
    public String getHomeData() {
        JSONObject respJson = new JSONObject();
        
        // 分层架构原则 - 通过Service层获取数据
        GreenhouseEntity greenhouseEntity = greenhouseService.getById(1L);
        respJson.put("greenhouse", greenhouseEntity);

        // 数据处理逻辑体现了单一职责和高内聚原则
        List<DeviceSoilRecordEntity> soilList = deviceSoilRecordService.getLastData();
        for (DeviceSoilRecordEntity record : soilList) {
            String name = record.getName();
            String value = record.getValue();
            
            if (value == null) {
                value = "0";
            }
            
            // 根据不同类型设置不同的单位和处理逻辑
            switch (name) {
                case "空气温度":
                    try {
                        double temp = Double.parseDouble(value);
                        // 处理温度数据，文档提到对于空气温度传感器获取到的数据是较大的整数，需要除以10才是最后的数值。
                        record.setValue(String.format("%.1f℃", temp / 10));
                    } catch (NumberFormatException e) {
                        record.setValue("0℃");
                    }
                    break;
                case "土壤温度":
                    record.setValue(value + "℃");
                    break;
                case "土壤含水率":
                    record.setValue(value + "%");
                    break;
                case "土壤电导率":
                    record.setValue(value + "us/cm");
                    break;
                case "土壤pH值":
                    record.setValue(value + "pH");
                    break;
                case "土壤氮含量":
                case "土壤磷含量":
                case "土壤钾含量":
                    record.setValue(value + "mg/kg");
                    break;
            }
        }
        respJson.put("soilList", soilList);

        List<DeviceMonitorRecordEntity> monitorRecordEntityList = deviceMonitorRecordService.getLastData();
        respJson.put("monitorList", monitorRecordEntityList);

        List<String> dateList = SoilComponent.getLastSevenDays();

        JSONArray trDataList = new JSONArray();
        JSONArray kqDataList = new JSONArray();
        JSONArray hslDataList = new JSONArray();

        for ( int i=0;i<dateList.size();i++){
            String date=dateList.get(i);
            String trData = deviceSoilRecordService.getTrDat(date, "土壤温度");

            if (trData == null) {
                trData = "0";
            }
            trDataList.add(trData);

            String kqData = deviceSoilRecordService.getTrDat(date, "空气温度");

            if (kqData == null) {
                kqData = "0";
            } else {
                try {
                    double temp = Double.parseDouble(kqData);
                    kqData = String.format("%.1f", temp / 10);
                } catch (NumberFormatException e) {
                    kqData = "0";
                }
            }
            kqDataList.add(kqData);

            String hslData = deviceSoilRecordService.getTrDat(date, "土壤含水率");

            if (hslData == null) {
                hslData = "0";
            }
            hslDataList.add(hslData);
        }

        JSONObject yJson = new JSONObject();
        JSONObject lJson = new JSONObject();
        JSONObject jJson = new JSONObject();

        String nameY = "土壤氮含量";
        yJson.put("name", nameY);
        yJson.put("value", deviceSoilRecordService.getZztDat(nameY));

        String nameL = "土壤磷含量";
        lJson.put("name", nameL);
        lJson.put("value", deviceSoilRecordService.getZztDat(nameL));

        String nameJ = "土壤钾含量";
        jJson.put("name", nameJ);
        jJson.put("value", deviceSoilRecordService.getZztDat(nameJ));

        JSONArray respArray = new JSONArray();

        respArray.add(yJson);
        respArray.add(lJson);
        respArray.add(jJson);

        String trData= JSON.toJSONString(trDataList);
        String kqData= JSON.toJSONString(kqDataList);
        String hslData= JSON.toJSONString(hslDataList);
        respJson.put("dateWeekList", dateList);
        respJson.put("trDataList", JSONArray.parseArray(trData));
        respJson.put("kqDataList", JSONArray.parseArray(kqData));
        respJson.put("hslDataList", JSONArray.parseArray(hslData));
        respJson.put("zztDataList", respArray);
        return respJson.toJSONString();
    }

    /**
     * CRUD操作方法
     * 设计原则体现：
     * 1. 接口隔离原则 - 提供简单明确的CRUD接口
     * 2. 命令查询分离(CQS) - 明确区分修改操作和查询操作
     */
    @GetMapping("/save")
    public String save(GreenhouseEntity greenhouseEntity) {
        greenhouseService.save(greenhouseEntity);
        return "success";
    }

    @GetMapping("/delete")
    public String delete(Long id) {
        greenhouseService.delete(id);
        return "success";
    }

    /**
     * 分页查询
     * 设计原则体现：
     * 1. 开放封闭原则 - 通过PageUtil封装分页逻辑，便于扩展
     * 2. 迪米特原则 - 控制器只与直接的依赖交互
     */
    @GetMapping("/page")
    public PageUtil<GreenhouseEntity> page(Integer pageIndex, Integer pageSize) {
        Page<GreenhouseEntity> page = greenhouseService.page(pageIndex , pageSize);
        // 使用PageUtil进行封装，体现了封装和复用原则
        PageUtil<GreenhouseEntity> pageUtil = new PageUtil<>();
        pageUtil.setRows(page.getContent());
        pageUtil.setTotal(page.getTotalElements());
        return pageUtil;
    }
}
